var mongoose = require('./index')

// 科室模型定义
var departmentSchema = new mongoose.Schema({
  // 科室基本信息
  name: {
    type: String,
    required: true,
    trim: true
  },
  
  // 科室描述
  description: {
    type: String,
    default: ''
  },
  
  // 医院数量
  hospitalCount: {
    type: Number,
    default: 0
  },
  
  // 价格范围
  priceRange: {
    type: String,
    default: '50-100'
  },
  
  // 可用时间段列表
  availableTimes: {
    type: [{
      date: { type: String, required: true }, // 日期，格式：YYYY-MM-DD
      timeSlots: [{
        time: { type: String, required: true }, // 时间段，如：08:30-09:30
        isAvailable: { type: Boolean, default: true }, // 是否可用
        patientId: { type: String, default: null } // 预约的患者ID
      }]
    }],
    default: []
  },
  
  // 科室图标
  icon: {
    type: String,
    default: 'https://img.icons8.com/color/48/000000/doctor-male.png'
  },
  
  // 科室状态 (启用/禁用)
  status: {
    type: String,
    enum: ['active', 'inactive'],
    default: 'active'
  },
  
  // 排序权重
  sortOrder: {
    type: Number,
    default: 0
  },
  
  // 创建时间
  createdAt: {
    type: Date,
    default: Date.now
  },
  
  // 更新时间
  updatedAt: {
    type: Date,
    default: Date.now
  }
})
const messageSchema = new mongoose.Schema({
    // 房间ID（医生-患者对话标识）
    roomId: {
        type: String,
        required: true,
        index: true
    },
    // 发送者ID
    senderId: {
        type: String,
        required: true
    },
    // 发送者类型（doctor/patient）
    senderType: {
        type: String,
        required: true,
        enum: ['doctor', 'patient']
    },
    // 消息内容
    content: {
        type: String,
        required: true
    },
    // 消息类型（text/image/file）
    // messageType: {
    //     type: String,
    //     default: 'text',
    //     enum: ['text', 'image', 'file']
    // },
    // 时间戳
    // timestamp: {
    //     type: Date,
    //     default: Date.now
    // },
    // 消息状态（sent/delivered/read）
    // status: {
    //     type: String,
    //     default: 'sent',
    //     enum: ['sent', 'delivered', 'read']
    // }
})
// , {
//     timestamps: true
// });

// 创建复合索引提高查询效率
// messageSchema.index({ roomId: 1, timestamp: 1 });

var Message = mongoose.model('Message', messageSchema);

// 更新时间中间件
departmentSchema.pre('save', function(next) {
  this.updatedAt = Date.now()
  next()
})

var Department = mongoose.model('Department', departmentSchema)

// 就诊人模型定义
var patientSchema = new mongoose.Schema({
  // 基本信息
  name: {
    type: String,
    required: [true, '姓名是必填项'],
    trim: true,
    minlength: [2, '姓名至少2个字符'],
    maxlength: [20, '姓名不能超过20个字符']
  },
  
  // 身份证号
  idCard: {
    type: String,
    required: [true, '身份证号是必填项'],
    unique: true,
    validate: {
      validator: function(v) {
        return /^\d{17}[\dXx]$/.test(v);
      },
      message: '请输入正确的身份证号码'
    }
  },
  
  // 出生日期
  birthDate: {
    type: Date,
    required: [true, '出生日期是必填项'],
    validate: {
      validator: function(v) {
        return v <= new Date();
      },
      message: '出生日期不能晚于今天'
    }
  },
  
  // 性别
  gender: {
    type: String,
    enum: ['male', 'female'],
    required: [true, '性别是必填项']
  },
  
  // 血型
  bloodType: {
    type: String,
    enum: ['A', 'B', 'AB', 'O'],
    required: false
  },
  
  // 婚姻状况
  maritalStatus: {
    type: String,
    enum: ['single', 'married', 'divorced', 'widowed'],
    required: false
  },
  
  // 专程就医
  specializedTreatment: {
    type: String,
    enum: ['yes', 'no'],
    required: false
  },
  
  // 手机号
  phone: {
    type: String,
    required: [true, '手机号是必填项'],
    validate: {
      validator: function(v) {
        return /^1[3-9]\d{9}$/.test(v);
      },
      message: '请输入正确的手机号码'
    }
  },
  
  // 紧急联系人
  emergencyContact: {
    type: String,
    required: false,
    trim: true
  },
  
  // 紧急联系人电话
  emergencyPhone: {
    type: String,
    required: false,
    validate: {
      validator: function(v) {
        if (!v) return true; // 允许为空
        return /^1[3-9]\d{9}$/.test(v);
      },
      message: '请输入正确的紧急联系人手机号码'
    }
  },
  
  // 地址
  address: {
    type: String,
    required: false,
    trim: true,
    maxlength: [200, '地址不能超过200个字符']
  },
  
  // 备注
  notes: {
    type: String,
    required: false,
    trim: true,
    maxlength: [500, '备注不能超过500个字符']
  },
  
  // 头像
  avatar: {
    type: String,
    required: false,
    maxlength: [10 * 1024 * 1024, '头像数据过大'] // 限制为10MB
  },
  
  // 用户ID（关联用户）
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: [true, '用户ID是必填项']
  },
  
  // 状态
  status: {
    type: String,
    enum: ['active', 'inactive'],
    default: 'active'
  },
  
  // 创建时间
  createdAt: {
    type: Date,
    default: Date.now
  },
  
  // 更新时间
  updatedAt: {
    type: Date,
    default: Date.now
  }
})

// 索引
patientSchema.index({ userId: 1, idCard: 1 });
patientSchema.index({ idCard: 1 }, { unique: true });

// 虚拟字段：年龄
patientSchema.virtual('age').get(function() {
  const today = new Date();
  const birthDate = new Date(this.birthDate);
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  
  return age;
});

// 确保虚拟字段在JSON中显示
patientSchema.set('toJSON', { virtuals: true });

// 更新时间中间件
patientSchema.pre('save', function(next) {
  this.updatedAt = Date.now()
  next()
})

var Patient = mongoose.model('Patient', patientSchema)

module.exports = {
  Department: Department,
  Patient: Patient
} 


